package com.easy.stock.other;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;


public class HttpUtil {

	public static int FETCHER_CONNECTION_TIMEOUT = 1000;
	public static int FETCHER_READ_TIMEOUT = 2000;
	public static int FETCHER_RETRY_NUM = 2;
	public static String LINE_SEP = System.getProperty("line.separator");

	public static String getUrl(String url, String charset) {

		if (url == null || url.length() == 0)
			return null;

		int retryTime = 0;
		String result = null;
		HttpURLConnection conn = null;
		while(retryTime < FETCHER_RETRY_NUM) {
			try {
				URL target = new URL(url);
		        conn = (HttpURLConnection) target.openConnection();
		        conn.setConnectTimeout(FETCHER_CONNECTION_TIMEOUT);
		        conn.setReadTimeout(FETCHER_READ_TIMEOUT);
		        conn.setRequestMethod("GET");
		        conn.connect();
		        
				if (conn.getResponseCode()!=HttpURLConnection.HTTP_OK) {
					conn.disconnect();
					continue;
				}
				
				BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
				String tmp = null;
				StringBuffer buf = new StringBuffer();
				while((tmp=reader.readLine())!=null) {
					buf.append(tmp).append(LINE_SEP);
				}
				result=buf.toString();
				break;	
			} catch (Exception e) {
				retryTime++;
				if(conn!=null) 
					conn.disconnect();
			}
		}
		
		return result;
	}
	
	
	
	public static String fetchByGet(String url, String charset, Map<String, String> headers) {

		if (url == null || url.length() == 0)
			return null;

		int retryTime = 0;
		String result = null;
		HttpURLConnection conn = null;
		while(retryTime < FETCHER_RETRY_NUM) {
			try {
				URL target = new URL(url);
		        conn = (HttpURLConnection) target.openConnection();
		        conn.setConnectTimeout(FETCHER_CONNECTION_TIMEOUT);
		        conn.setReadTimeout(FETCHER_READ_TIMEOUT);
		        conn.setRequestMethod("GET");
		        
		        if(headers!=null) {
		        	for(Entry<String, String> entry : headers.entrySet()) {
		        		conn.setRequestProperty(entry.getKey(), entry.getValue());
		        	}
		        }
		        
		        
		        conn.connect();
		        
				if (conn.getResponseCode()!=HttpURLConnection.HTTP_OK) {
					conn.disconnect();
					continue;
				}
				
				BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
				String tmp = null;
				StringBuffer buf = new StringBuffer();
				while((tmp=reader.readLine())!=null) {
					buf.append(tmp).append(LINE_SEP);
				}
				result=buf.toString();
				break;	
			} catch (Exception e) {
				retryTime++;
				if(conn!=null) 
					conn.disconnect();
			}
		}
		
		return result;
	}

}
